package com.atguigu.dwm.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dwm.common.util.SqlUtil;
import com.atguigu.dwm.ds.bean.TDsTaskDefinition;
import com.atguigu.dwm.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dwm.ds.service.TDsTaskDefinitionService;
import com.atguigu.dwm.model.bean.DmTable;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2024-07-08
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {



    public List<TDsTaskDefinition> getTaskDefinitionList(List<DmTable> tableList){

        List<String> tableNameList = tableList.stream().map(table ->"'"+ table.getSchemaName() + "." + table.getTableName()+"'").collect(Collectors.toList());
        // in ( 'a.x','a.y')
        String inSql = tableNameList.stream() .collect(Collectors.joining(","));
        List<TDsTaskDefinition> taskDefinitionList = baseMapper.getTaskDefinitionList(inSql);
        for (TDsTaskDefinition tDsTaskDefinition : taskDefinitionList) {
            this.extractSqlForDefinition(tDsTaskDefinition);
        }

        return taskDefinitionList;

    }

    private void extractSqlForDefinition(TDsTaskDefinition tDsTaskDefinition) {
        String taskParams = tDsTaskDefinition.getTaskParams();
        //1 提取taskParams的rawScript
        JSONObject jsonObject = JSON.parseObject(taskParams);
        String rawScript = jsonObject.getString("rawScript");

        //2 其实坐标
        int startIdx = rawScript.indexOf("with");
        if(startIdx== -1){
            startIdx=  rawScript.indexOf("insert");
        }
        if(startIdx== -1){
            return  ;
        }

        //3
        int endIdx = rawScript.indexOf(";",startIdx);
        if (endIdx==-1){
            endIdx=  rawScript.indexOf("\"",startIdx);
        }
        if (endIdx==-1){
            return  ;
        }
        //4 截取
        tDsTaskDefinition.setSql(rawScript.substring(startIdx,endIdx).replace("\n"," "));

    }
}
